package com.syx.server.service;

import com.syx.common.Message;
import com.syx.common.MessageType;
import com.syx.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author 邵一鑫
 * @date 2024/1/13 22:47
 * 这是服务器，监听 8010，等来客户端连接，并保持统计
 */
public class QQServer {

    private ServerSocket serverSocket = null;

    private static HashMap<String, User> users = new HashMap<>();   // 模拟数据库，存放合法用户

    // 静态代码块在类加载的时候执行一次
    static {
        users.put("100", new User("100", "100100"));
        users.put("200", new User("200", "200200"));
        users.put("300", new User("300", "300300"));
        users.put("saber", new User("saber", "123456"));
        users.put("两仪式", new User("两仪式", "123456"));
        users.put("芙莉莲", new User("芙莉莲", "123456"));
        users.put("菲伦", new User("菲伦", "123456"));
        users.put("明日香", new User("明日香", "123456"));
    }

    public QQServer() {
        System.out.println("服务端在8010端口监听...");

        try {
            serverSocket = new ServerSocket(8010);
            // 保持监听
            while (true) {
                // 当没有连接请求时，会在这里阻塞
                Socket socket = serverSocket.accept();
                // 得到 socket 关联的输入流
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                // 得到 socket 关联的输出流
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                // 验证登录
                User user = (User) ois.readObject();
                if (checkUser(user.getUserId(), user.getPwd())) {
                    System.out.println("用户" + user.getUserId() + "登录成功");
                    // 登陆成功，创建线程持有 socket
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(user.getUserId(), socket);
                    serverConnectClientThread.start();
                    // 集合管理socket
                    ManageConnectClientThread.addServerConnectClientThread(user.getUserId(), serverConnectClientThread);
                    // 发送消息
                    oos.writeObject(new Message("登录失败", MessageType.MESSAGE_LOGIN_SUCCEED));
//                    socket.shutdownOutput();
                } else {
                    // 登录失败，发送消息，关闭 socket
                    oos.writeObject(new Message("登录失败", MessageType.MESSAGE_LOGIN_FAIL));
//                    socket.shutdownOutput();
                    socket.close();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 退出循环说明不再监听，关闭资源
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 验证用户是否合法
     * @param userId id
     * @param pwd 密码
     * @return
     */
    private boolean checkUser(String userId, String pwd) {
        User user = users.get(userId);
        if (user == null) {
            // 用户不存在
            return false;
        }
        if (!user.getPwd().equals(pwd)) {
            // 密码错误
            return false;
        }
        return true;
    }
}
